package com.qiniu.githubdata.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.githubdata.entity.Repository;
import com.qiniu.githubdata.job.GitHubRepoFetcher;
import com.qiniu.githubdata.mapper.RepositoryMapper;
import org.kohsuke.github.GHRepository;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author: mayixiang
 * @Date: 2024-10-29 22:15
 * @Description:
 */
@Service
public class RepositoryService extends ServiceImpl<RepositoryMapper, Repository> {
    @Resource
    @Lazy
    private GitHubRepoFetcher gitHubRepoFetcher;
    @Resource
    private RepositoryMapper repositoryMapper;

    public double getImportance(Repository repository) {
        if(repository.getImportance()>0){
            return repository.getImportance();
        }
        double importance = 0;
        int stars = repository.getStars(), forks = repository.getForks(), issues = repository.getIssues();
        double starsWeight = 0.3, forksWeight = 0.3, issuesWeight = 0.4;
        importance = (double)stars * starsWeight + (double)forks * forksWeight + (double)issues * issuesWeight;
        repository.setImportance(importance);
        this.update(repository, new QueryWrapper<Repository>().eq("id", repository.getId()));
        return importance;
    }
    public List<Repository> getTop6RepoByOwner(String owner) throws IOException {
        Map<String, GHRepository> repos = gitHubRepoFetcher.getReposByOwner(owner);
        List<Repository> repositoryList = repositoryMapper.selectList(new LambdaQueryWrapper<Repository>().
                eq(Repository::getOwner, owner).orderByDesc(Repository::getStars).last("limit 6"));
        if (repositoryList.isEmpty()) {
            for (GHRepository ghRepository : repos.values()) {
                Repository repository = gitHubRepoFetcher.convertGHRepoToRepo(ghRepository);
                repositoryList.add(repository);
            }
        }
        return repositoryList;
    }
}